<?php

class ContentManager extends TModule 
{
	// -------------------- basic functions --------------------
	public function addContent($name, $text)
	{
		if($this->hasContent($name))
		{
			return $this->updateContent($name, $text);
		}
		else
		{
			$content = new ContentRecord();
			$content->setData($name, $text);
			if($content->save())
				return $content;
			else
				return null;
		}
	}
	
	public function deleteContent($name)
	{
		return ContentRecord::finder()->deleteByPk($name);
	}
	
	public function updateContent($name, $text)
	{	
		$contentRecord = new ContentRecord();
		$contentRecord->setData($name, $text);
		return $this->updateContentByContentRecord($contentRecord);
	}
	
	public function updateContentByContentRecord($contentRecord)
	{
		if($contentRecord instanceof ContentRecord)
		{
			$finder = ContentRecord::finder();
			$name = $contentRecord->getName();
			if($rec = $finder->findByPk($name))
			{
				if($rec->equals($contentRecord))
					return $rec;
				$rec->setDataByContentRecord($contentRecord);
				if($rec->save())
					return $rec;
			}
		}
		return null;
	}
	
	public function getContentByName($name)
	{
		return ContentRecord::finder()->findByName($name);
	}
	
	// -------------------- extended functions --------------------
	public function getContentList()
	{	
		return ContentRecord::finder()->findAll();
	}
	
	public function hasContent($name)
	{
		return $this->getContentByName($name) != null;
	}
}

?>